package com.book.system.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.book.common.core.domain.entity.AppUser;
import com.book.system.domain.UserTaskCompletion;
import com.book.system.mapper.UserTaskCompletionMapper;
import com.book.system.service.IAppUserService;
import com.book.system.service.IUserTaskCompletionService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author Bigboss
 * @create 2024-11-10 17:09
 */
@Service
public class UserTaskCompletionServiceImpl extends ServiceImpl<UserTaskCompletionMapper, UserTaskCompletion> implements IUserTaskCompletionService {

    private final UserTaskCompletionMapper userTaskCompletionMapper;

    private final IAppUserService appUserService;

    public UserTaskCompletionServiceImpl(UserTaskCompletionMapper userTaskCompletionMapper, IAppUserService appUserService) {
        this.userTaskCompletionMapper = userTaskCompletionMapper;
        this.appUserService = appUserService;
    }

    /**
     * 用户完成任务
     * @param entity
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int completionTask(UserTaskCompletion entity) {
        int rows = userTaskCompletionMapper.insert(entity);
        if(rows > 0){
            AppUser user = appUserService.getById(entity.getAppUserId());
            if(ObjectUtil.isNotNull(user)){
                user.setGoldCoin(user.getGoldCoin() + entity.getRewardEarned());
                appUserService.updateById(user);
            }
        }
        return rows;
    }
}
